import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function hasPermissionRoutes(newRoutes, route) {
  if (route.meta && route.meta.modulePath) {
    return newRoutes.some(newRoute => route.meta.modulePath == newRoute.modulePath)
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, newRoutes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermissionRoutes(newRoutes, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, newRoutes)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
  }
}

const actions = {
  //在src/permission.js中调用  const accessRoutes = await store.dispatch('permission/generateRoutes', routes)
  //newRoutes 就是 routes
  generateRoutes({ commit }, newRoutes) {
    return new Promise(resolve => {

      const accessedRoutes = filterAsyncRoutes(asyncRoutes, newRoutes)

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  clearRouters({ commit }) {
    return new Promise(resolve => {
      commit('RESET_ROUTES')
      resolve()
    })
  }
}

// const actions = {
//   generateRoutes({ commit }, roles) {
//     return new Promise(resolve => {
//       let accessedRoutes
//       if (roles.includes('admin')) {
//         accessedRoutes = asyncRoutes || []
//       } else {
//         accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
//       }
//       commit('SET_ROUTES', accessedRoutes)
//       resolve(accessedRoutes)
//     })
//   }
// }

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
